package com.niu.wm.web.controller;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;

import com.alibaba.fastjson.JSONArray;
import com.niu.wm.core.ResponseObject;
import com.niu.wm.core.error.BizException;
import com.niu.wm.core.error.GlobalErrorCode;
import com.niu.wm.model.Dict;
import com.niu.wm.model.User;
import com.niu.wm.service.DictService;

@Controller
@RequestMapping(value = "/dict")
public class DictController extends BaseController{
	@Autowired
	private DictService dictService;
	
	
	@RequestMapping(value = "/main")
    public String dictMain(){
		return "dict/main";
	}
	
	
	
	@RequestMapping(value = "/edit")
    public String dictEdit(Long id, Model model){
		Dict dict = dictService.load(id);
		model.addAttribute("dict", dict);
		
		if (dict.getParentId() != null) {
			Dict pDict = dictService.load(dict.getParentId());
			model.addAttribute("pDict", pDict);
		}
		
		return "dict/detail";
	}
	
	@RequestMapping(value = "/create")
    public String dictCreate(Long parentId, Model model){
		
		Dict pDict = dictService.load(parentId);
		model.addAttribute("pDict", pDict);
		
		return "dict/detail";
	}
	
	@RequestMapping(value = "/{id}")
    @ResponseBody
    public ResponseObject<Dict> getDict(@PathVariable("id") Long id){
		Dict dict = dictService.load(id);
		if(dict == null)
			throw new BizException(GlobalErrorCode.DATA_NOT_EXIST, "数据没找到");
		
		return new ResponseObject<Dict>(dict);
	}
	
	@RequestMapping(value = "/save")
    @ResponseBody
    public ResponseObject<Dict> save(Dict dict){
		User user = this.getCurrentUser();
		
		if(dict.getId() == null)
			dictService.add(user, dict);
		else
			dictService.update(user, dict);
		
		return new ResponseObject<Dict>(dict);
	}
	
	public static void main(String... args){
		System.out.println("hello");
	}
}
